import Vue from 'vue'
import VueRouter from 'vue-router'
import { routes } from './routes'
import store from '@/store'
import loadMenus from './asyncRouter'

// 进度条
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
Nprogress.configure({ showSpinner: false })

Vue.use(VueRouter)

const router = new VueRouter({
    routes
})

// 免登录白名单
const whiteList = ['/login']

// 路由前置
router.beforeEach(async (to, form, next) => {
    Nprogress.start()
    if (whiteList.includes(to.path)) {
        if (['/login', '/Login'].includes(to.path) && localStorage.getItem('token')) {
            next({...form, replace: true})
        } else {
            next()
        }
    } else if (!localStorage.getItem('token')) {
        next('/login')
    } else if (!Object.keys(store.state.user.userInfo).length) {
        await store.dispatch('getInfo')
        await store.dispatch('getRouters')
        await loadMenus()
        next({...to, replace: true})
    } else {
        next()
    }
})

// 路由后置
router.afterEach(_=>{
    Nprogress.done()
})

export default router
